<?
$bess    = array();
$xValues = array();
$yValues = array();
$xval    = array();
 
$logEvent  = array();
$logMinute = array();
$logHour   = array();
$logDay    = array();
$logMonth  = array();
$logYear   = array();
$logUser   = array();
$logTemp   = array();

$userEntry = array();

$data      = array();
$cdata     = array();
$tick      = array();

$freq      = array();


//==========================================
function convTemp($value)
//==========================================
{
    $res = 61.41 - 0.078*$value;
    return($res);
}

//==========================================
function addZero($value)
//==========================================
{
  if($value < 10)$value = '0'.$value;
  return($value);
}

//==========================================
function readCurrentValue($user)
//==========================================
{
   
  $file = "bess_$user.cur";
  if(!file_exists($file))
    {
      return("-");;
    }

  $in = fopen($file,"r");
  if($in)
    {
      $row = fgets($in);
    }  
  fclose($in);
  return($row);
}

//==========================================
function readCurrentSum($user,$date)
//==========================================
{
  //$date  = date("Y");	
  $file  = "bess-$user-$date.sum"; 
  if(!file_exists($file))
    {
      return("-");
    }
  $in = fopen($file,"r");
  if($in)
    {
      $row = fgets($in);
    }  
  fclose($in);
  $row = $row/1000;
  return($row);
}

//==========================================
function fft()
//==========================================
{
  global $freq;

  $wH = 500;
  $width = 5;
  $floor = 0;
  $roof = 1000;
  $start = 40;


  $pp = 0;
  $maxV = 0;
  for ($ii=$start;$ii<5000;$ii++)
    {
      $temp = $freq[$ii];
      if($temp > 0)
	{
	  //echo("$ii $temp<br>");
	  if($temp > $maxV)$maxV = $temp;
	}
    }

  //$maxV = 1000;
  echo("max=$maxV<br>");
  $scale = $maxV/$wH;

  echo("<script>");
  echo("function draw(){");
  echo("var canvas = document.getElementById(\"myFFT\");");
  echo("var context = canvas.getContext(\"2d\");");
  for($ii=$start;$ii<=4000;$ii++)
    {
      $temp = $freq[$ii];
      if($temp >= $floor)
	{
	  $value  = ($temp-$floor)/$scale;
	}
      if($temp >= $roof)$value = $roof;
      $yy  = $wH  - $value;
      $xx  = ($ii-1-$pos)*$width;
      echo("context.beginPath();");
      echo("context.rect($xx,$yy,$width,$value);");
      echo("context.fillStyle = \"red\";");
      echo("context.fill();");
      echo("context.lineWidth = 1;");
      echo("context.strokeStyle = \"black\";");
      echo("context.stroke();");

    }

  echo("};");
  echo("</script>");

 echo("<div id=\"dgraph\" style=\"font-family:Courier,monospace; font-size:11px;float:left; border : solid 1px #000000; background : #A9BCF5; color : #000000;  text-align:left; padding : 3px; width :100%; height:$px; overflow : auto; margin-left:0px; margin-bottom:10px;line-height:1.0em; \">");

  echo("<canvas id=\"myFFT\" width=\"20000\" height=\"500\"</canvas>"); 
  echo("</div>");

}

//==========================================
function readLogFile($file)
//==========================================
{
  global $user,$userEntry,$freq;
  global $logEvent,$logMinute,$logHour,$logDay,$logMonth,$logYear,$logUser,$logTemp;

  
  if(!$file)
    {
      echo("readLogFile: no file ($file)");
      return;
    }
  
  $event   = 0;
  $nEvents = 0;
  $in = fopen($file,"r");
  if($in)
    {
      //$dataLabel = trim(fgets($in));
      while (!feof($in))
	{
	  $nEvents++;

	  $oldMinute = $minute;
	  $oldPower = $power;

	  $row = fgets($in);
	  sscanf($row,"%s %s %d %d %d %d %d %d",$date,$time,$msec,$puls,$power,$base,$sigmax,$temp);
	  $delta = $power - $oldPower;
	  $freq[$delta]++;
	  // echo("freq = $delta<br>");
	  $info    = date_parse("$date $time");
	  $year    = $info["year"]+1;
	  $month   = $info["month"]+1;
	  $day     = $info["day"]+1;
	  $hour    = $info["hour"]+1;
	  $minute  = $info["minute"]+1;
	  $second  = $info["second"]+1;


	  if($oldMinute != $minute)$event = 0;
	  $logTemp[$user][$year][$month][$day][$hour][$minute][$event] = $temp;
	  $logEvent[$user][$year][$month][$day][$hour][$minute][$event] = $power;
	  $logMinute[$user][$year][$month][$day][$hour][$minute] += $puls;
	  //$temp = $logMinute[$user][$year][$month][$day][$hour][$minute];
	  //echo("$event [$user][$year][$month][$day][$hour][$minute]xx $temp<br>");
	  $logHour[$user][$year][$month][$day][$hour] += $puls;
	  $logDay[$user][$year][$month][$day] += $puls;
	  $logMonth[$user][$year][$month] += $puls;
	  $logYear[$user][$year] += $puls;
	  //$temp = $logYear[$user][$year];
	  //echo("bbb [$user][$year] $temp<br>");
	  $logUser[$user] += $puls;

	  $event++;
        }	  
    }
  else
    echo("readLogFile Error <br>");

  fclose($in);
  return($nEvents);

}

//==========================================
function writeUserConfig($conf)
//==========================================
{

  global $bess;
  
  $file = "bess_$conf.conf";
  //echo("benny $file");
  if(!$file)
    {
      echo("writeUserConfig: no file ($file)");
      return;
    }
  
  $out = fopen($file,"w");
  if($out)
    {
      fprintf($out,"IMPLEV: %d\n",$bess['implev']);
      fprintf($out,"LOGLEV: %d\n",$bess['loglev']);
    }
  else
    echo("Not able to open user config file write ($file)");  
  
  fclose($out); 
}


//===================================================
function histogram($mode,$intv,$height,$floor,$roof,$pos)
{
  global $data,$cdata,$pulsData,$bess,$tick;


  if(!isset($floor))$floor = 0;

  if(!isset($height))$height = 20;


  if($intv == 'detail')
    {
      $nData = 0;
      for($ii=1;$ii<14400;$ii++) // 24*60*10
	{
	  if($data[$ii])$nData++;
	}
      $conv = 1;
    }

  if($intv == 'minute')
    {
      $back = 'hour';
      $nData = 0;
      for($ii=1;$ii<20;$ii++)
	{
	  if($data[$ii])$nData++;
	}
      $conv = 1;
    }

  if($intv == 'hour')
    {
      $back = 'day';
      $nData = 60;
      $conv = 1/60;
    }
  if($intv == 'day')
    {
      $back = 'month';
      $nData = 24;
      $conv = 1;
    }
  if($intv == 'month')
    {
      $back = 'year';
      $nData = 32;
      $conv = 24;
    }
  if($intv == 'year')
    {
      $back = 'year';
      $nData = 12;
      $conv = 31*24;
    }

  if(!$nData)
    {
      echo("Error: Number of data = 0<br>");
      exit();
    }

  if($pos > $nData)$pos = 1;

  $tot = 0;
  for($ii=1;$ii<=$nData;$ii++)
    {
      $tot +=$data[$ii];
    }

  if($intv == 'minute')$tot = $tot/$nData;

  if($mode == 'values')
    {
      echo("<hr><b>Consumption $intv: $tot Watt  [$ndata]</b><br>");
      for($ii=1;$ii<=$nData;$ii++)
	{
	  if($data[$ii])echo("$ii=$data[$ii]<br> "); 
	} 
      return;
    }


  $px = $height*11+60;$px = $px.'px';

  $scale = ($roof-$floor)/$height;
  if($scale <= 0)
    {
      echo("Warning: Scale error ($floor, $roof)<br>");
      $scale = 1;
    }

  $tot     = round($tot,2);
  $kwh     = $data['energy'];
  $date    = $data['date'];
  $current = $data['current'];

  $next = $current+1;
  $prev = $current-1;

      echo("<div id=\"graph\" style=\"font-family:Courier,monospace; font-size:11px;float:left; border : solid 1px #000000; background : #A9BCF5; color : #000000;  text-align:left; padding : 3px; width :100%; height:$px; overflow : auto; margin-left:0px; margin-bottom:10px;line-height:1.0em; \">");

      echo("<b>$kwh kWh [$nData] X-axis: ");
      echo("<a href=index.php?a=graph&x=$intv&y=$prev> << </a>");
      echo("<a href=index.php?a=graph&x=$back>$intv</a>");
      echo("<a href=index.php?a=graph&x=$intv&y=$next> >> </a>");
      echo(" Y-axis: $floor-$roof  Pos: $pos Date:$date <font color=\"red\">o</font>=$scale</b><br/>");
      
      for($jj=$height;$jj>0;$jj--)
	{
	  for($ii=$pos;$ii<=$nData;$ii++)
	    {
	      if($intv != 'hour' && $ii == $pos)
		{
		  if($jj%($height/5) == 0)
		    echo('-');
		  else
		    echo('|');
		}

	      if($intv == 'hour' && ($ii-1)%10 == $pos)
		{
		  if($jj%($height/5) == 0)
		    echo('-');
		  else
		    echo('|');
		}


	      $value  = 0;
	      $cvalue = 0;
	      $temp   = $data[$ii];
	      $ctemp  = $cdata[$ii];
	      if($temp >= $floor)
		{
		  $value  = round(($temp-$floor)/$scale);
		  $cvalue = round(($ctemp-$floor)/$scale);
		}


	      if($value >= $jj)
		{
		  printf("<font color=\"red\">o</font>");
		}
	      else
		echo("&nbsp");

	      if($intv=='day')
		{
		  if($cvalue >= $jj)
		    {
		      printf("<font color=\"black\">|</font>");
		    }
		  else
		    echo("&nbsp");
		}


	      
	      if($intv=='day')echo('&nbsp');
	      if($intv=='year')echo('&nbsp&nbsp');
	      if($intv=='month')echo('&nbsp&nbsp');
	    }
	  echo("<br/>");
	}


      // X-axis

      if($intv=='hour')
	{
	  for($ii=$pos;$ii<$nData+4*24;$ii++)echo("_");
	  echo("<br/>");
	  echo("&nbsp");
	  for($ii=$pos;$ii<$nData;$ii++)
	    {
	      //$temp = $ii/10;
	      if($ii%10==0)printf("%d",$ii);
	      else 
		echo("&nbsp");
	    }
	}
      if($intv=='day')
	{
	  for($ii=$pos;$ii<=$nData;$ii++)echo("___");
	  echo("<br/>");
	  echo("&nbsp");
	  for($ii=$pos;$ii<=$nData;$ii++)
	    {
	      $temp=$ii-1;
	      if($temp < 0)$temp=' ';
	      echo("<b><a href=index.php?a=graph&x=hour&y=$ii>$temp</a></b>");echo("&nbsp");
	      //echo("$temp&nbsp");
	      if($ii < 10)echo("&nbsp");
	    }
	}
      if($intv=='month')
	{
	  for($ii=$pos;$ii<=$nData;$ii++)echo("___");
	  echo("<br/>");
	  echo("&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp");
	  for($ii=$pos+2;$ii<=$nData;$ii++)
	    {
	      $temp=$ii-1;
	      if($temp < 0)$temp=' ';
	      echo("<b><a href=index.php?a=graph&x=day&y=$ii>$temp</a></b>");echo("&nbsp");
	      //echo("$temp&nbsp");
	      if($ii < 10)echo("&nbsp");
	    }
	}
      if($intv=='year')
	{
	  for($ii=$pos;$ii<=$nData;$ii++)echo("___");
	  echo("<br/>");
	  echo("&nbsp");
	  for($ii=$pos;$ii<=$nData;$ii++)
	    {
	      $temp=$ii-1;
	      if($temp < 0)$temp=' ';
	      echo("<b><a href=index.php?a=graph&x=month&y=$ii>$temp</a></b>");echo("&nbsp");
	      //echo("$temp&nbsp");
	      if($ii < 10)echo("&nbsp");
	    }
	}
      if($intv=='detail')
	{
	  for($ii=$pos;$ii<=$nData+1;$ii++)echo("_");
	  echo("<br/>");
	  echo("&nbsp");
	  for($ii=$pos;$ii<$nData;$ii++)
	    {
	      if($flag==2)$flag=0;
	      if($flag==1)$flag=2;
	      $temp = $tick['hour'][$ii];
	      $temp2 = $tick['minute'][$ii];
	      if($temp) //hour
		{
		  $temp = $temp - 1;
		  if($temp > 9)$flag = 1;
		  printf("<b><a href=index.php?a=pos&x=$ii>%d</a></b>",$temp);
		}
	      else if ($temp2) // minute
		{
		  $temp2 = $temp2 - 1;
		  if($temp2%10 == 0)
		    {
		      $temp2 = $temp2/10;
		      printf("<i><a href=index.php?a=pos&x=$ii>%d</a></i>",$temp2);
		    }
		  else
		    printf(".");
		}
	      else if($flag < 2)
		echo("&nbsp");


	    }
	}
  echo("</div>");

}

//===================================================
function canHistogram($mode,$intv,$height,$floor,$roof,$pos)
{
  global $data,$cdata,$pulsData,$bess,$tick;


  if(!isset($floor))$floor = 0;

  if(!isset($height))$height = 20;



  if($intv == 'detail')
    {
      $nData = 0;
      for($ii=1;$ii<14400;$ii++) // 24*60*10
	{
	  if($data[$ii])$nData++;
	}
      $conv = 1;
      $barWidth = 3;
    }

  if($intv == 'minute')
    {
      $barWidth = 10;
      $back = 'hour';
      $nData = 0;
      for($ii=1;$ii<20;$ii++)
	{
	  if($data[$ii])$nData++;
	}
      $conv = 1;
    }

  if($intv == 'hour')
    {
      $barWidth = 8;
      $back = 'day';
      $nData = 60;
      $conv = 1/60;
    }
  if($intv == 'day')
    {
      $barWidth = 20;
      $back = 'month';
      $nData = 24;
      $conv = 1;
    }
  if($intv == 'month')
    {
      $barWidth = 20;
      $back = 'year';
      $nData = 32;
      $conv = 24;
    }
  if($intv == 'year')
    {
      $barWidth = 20;
      $back = 'year';
      $nData = 12;
      $conv = 31*24;
    }

  if(!$nData)
    {
      echo("Error: Number of data = 0<br>");
      exit();
    }

  if($pos > $nData)$pos = 1;

  $tot = 0;
  for($ii=1;$ii<=$nData;$ii++)
    {
      $tot +=$data[$ii];
    }

  if($intv == 'minute')$tot = $tot/$nData;


  $px = $height*11+60;
  $cHeight = $px;
  $px = $px.'px';

  $scale = ($roof-$floor)/$cHeight;
  if($scale <= 0)
    {
      echo("Warning: Scale error ($floor, $roof)<br>");
      $scale = 1;
    }

  $tot     = round($tot,2);
  $kwh     = $data['energy'];
  $date    = $data['date'];
  $current = $data['current'];

  $next = $current+1;
  $prev = $current-1;
  $wW = $nData*$barWidth;
  $wH = $cHeight;
  $bias = 20;

  $width = round($wW/$nData);

  //echo("$nData,wW=$wW,wH=$wH,scale=$scale<br>");
  // Jag fattar inte varfor loopen nedan behovs ???
  for($ii=$pos;$ii<=$nData;$ii++)
    {
      $temp = $data[$ii];
      if($temp >= $floor)
	{
	  $value  = ($temp-$floor)/$scale;
	}
    }

  echo("<script>");
  echo("function draw(){");
  echo("var canvas = document.getElementById(\"myCanvas\");");
  echo("var context = canvas.getContext(\"2d\");");
  for($ii=$pos;$ii<=$nData;$ii++)
    {
      $temp = $data[$ii];
      if($temp >= $floor)
	{
	  $value  = ($temp-$floor)/$scale;
	}
      $yy  = $wH  - $value;
      $xx  = ($ii-1-$pos)*$width;
      echo("context.beginPath();");
      echo("context.rect($xx,$yy,$width,$value);");
      echo("context.fillStyle = \"green\";");
      echo("context.fill();");
      echo("context.lineWidth = 1;");
      echo("context.strokeStyle = \"black\";");
      echo("context.stroke();");

    }

  echo("};");
  echo("</script>");

 echo("<div id=\"cgraph\" style=\"font-family:Courier,monospace; font-size:11px;float:left; border : solid 1px #000000; background : #A9BCF5; color : #000000;  text-align:left; padding : 3px; width :100%; height:$px; overflow : auto; margin-left:0px; margin-bottom:10px;line-height:1.0em; \">");

  echo("<canvas id=\"myCanvas\" width=\"$wW\" height=\"$cHeight\"</canvas>"); 
  echo("</div>");
}


//===================================================
function xhistogram($canvas)
{
  global $wH,$wW,$data,$xAxis,$yAxis,$nData,$dmax,$xval;
  global $dataType,$dataLabel;
  
  echo("<script>");
  echo("window.onload = function(){");
  echo("var canvas = document.getElementById(\"$canvas\");");
  echo("var context = canvas.getContext(\"2d\");");
  
  $bias = 10;

  $width = round($wW/$nData);
  $scale = ($wH-$bias)/$dmax;
  for($ii=1;$ii<=$nData;$ii++)
    {
      //$height = $ii*($wH/$nData);
      $height = round($data[$ii]*$scale);
      //$yy     = $wH - $ii*10;
      $yy     = round($wH - $bias - $height);
      $xx     = round(($ii-1)*$width);
      echo("context.beginPath();");
      echo("context.rect($xx,$yy,$width,$height);");
      echo("context.fillStyle = \"green\";");
      echo("context.fill();");
      echo("context.lineWidth = 1;");
      echo("context.strokeStyle = \"black\";");
      echo("context.stroke();");

      echo("context.fillStyle = \"blue\";");
      echo("context.font=\"8pt Helvetica\";");
      $pos = round($xx + $width/3);
      $temp = $xval[$ii];
      echo("context.fillText(\"$temp\",$pos, $wH);");
    }
  // Draw X-axis at top
  echo("context.moveTo(0, 0);");
  echo("context.lineTo($wW, 0);");
  echo("context.lineWidth = 2;");
  echo("context.strokeStyle = \"black\";");
  echo("context.stroke();");

  // Draw Y-axis
  echo("context.moveTo(0, 0);");
  echo("context.lineTo(0, $wH);");
  echo("context.lineWidth = 2;");
  echo("context.strokeStyle = \"black\";");
  echo("context.stroke();");

  echo("context.fillStyle = \"blue\";");
  echo("context.font=\"8pt Helvetica\";");
  echo("context.fillText(\"$dmax\",10,10);");
  echo("};");
  echo("</script>");
}

//===================================================
function chistogram($canvas)
{

  echo("<script type=\"application/javascript\">");
  echo("function draw(){");
  echo("var canvas = document.getElementById(\"$canvas\");");
  echo("var context = canvas.getContext(\"2d\");");
  

      echo("context.beginPath();");
      echo("context.rect(1,1,10,10);");
      echo("context.fillStyle = \"green\";");
      echo("context.fill();");
      echo("context.lineWidth = 1;");
      echo("context.strokeStyle = \"black\";");
      echo("context.stroke();");

      echo("context.fillStyle = \"blue\";");
      echo("context.font=\"8pt Helvetica\";");
      $pos = round($xx + $width/3);
      $temp = $xval[$ii];
      echo("context.fillText(\"Benny\",1, 20);");
 
  // Draw X-axis at top
  echo("context.moveTo(0, 0);");
  echo("context.lineTo(10, 0);");
  echo("context.lineWidth = 2;");
  echo("context.strokeStyle = \"black\";");
  echo("context.stroke();");

  // Draw Y-axis
  echo("context.moveTo(0, 0);");
  echo("context.lineTo(0, 20);");
  echo("context.lineWidth = 2;");
  echo("context.strokeStyle = \"black\";");
  echo("context.stroke();");

  echo("context.fillStyle = \"blue\";");
  echo("context.font=\"8pt Helvetica\";");
  echo("context.fillText(\"88\",10,10);");
  echo("};");
  echo("</script>");
}



?>
